import plugin from '../../../lib/plugins/plugin.js'
import { Version, Plugin_Name , Config } from '../components/index.js'
import fs from "node:fs";
import { createRequire } from "module";

const require = createRequire(import.meta.url)
const { execSync } = require('child_process')

export class admin extends plugin {
    constructor() {
        super({
            name: "小月版本信息",
            event: "message",
            priority: 500,
            rule: [
                {
                    reg: '^#?小月(插件)?更新日志$',
                    fnc: 'update_log',
                },
            ],
        });
    }
    
    async update_log() {
        if (this.getPlugin(Plugin_Name)) {
            this.e.reply(await this.getLog(Plugin_Name));
        }
        return true;
    }

    getPlugin (plugin) {
        let path = `./plugins/${plugin}/.git`
        if (!fs.existsSync(path)) return false
        return plugin
    }

    async getLog (plugin) {
        let cm = 'git log  -20 --oneline --pretty=format:"%h||[%cd]  %s" --date=format:"%m-%d %H:%M"'
        if (plugin) {
            cm = `cd ./plugins/${plugin}/ && ${cm}`
        }
        let logAll
        try {
            logAll = execSync(cm, { encoding: 'utf-8' })
        } catch (error) {
            this.reply(error.toString())
        }

        if (!logAll) return false

        logAll = logAll.split('\n')

        let log = []
        for (let str of logAll) {
            str = str.split('||')
            if (str[0] == this.oldCommitId) break
            if (str[1].includes('Merge branch')) continue
            log.push(str[1])
        }
        let line = log.length
        log = log.join('\n\n')

        if (log.length <= 0) return ''

        let end = ''

        log = await this.makeForwardMsg(`${plugin}更新日志，共${line}条`, log, end)

        return log
    }

    async makeForwardMsg (title, msg, end) {
        let nickname = Bot.nickname
        if (this.e.isGroup) {
            let info = await Bot.getGroupMemberInfo(this.e.group_id, Bot.uin)
            nickname = info.card ?? info.nickname
        }
        let userInfo = {
            user_id: Bot.uin,
            nickname
        }

        let forwardMsg = [
            {
                ...userInfo,
                message: title
            },
            {
                ...userInfo,
                message: msg
            }
        ]

        if (end) {
            forwardMsg.push({
                ...userInfo,
                message: end
            })
        }

        /** 制作转发内容 */
        if (this.e.isGroup) {
            forwardMsg = await this.e.group.makeForwardMsg(forwardMsg)
        } else {
            forwardMsg = await this.e.friend.makeForwardMsg(forwardMsg)
        }

        /** 处理描述 */
        forwardMsg.data = forwardMsg.data
          .replace(/\n/g, '')
          .replace(/<title color="#777777" size="26">(.+?)<\/title>/g, '___')
          .replace(/___+/, `<title color="#777777" size="26">${title}</title>`)

        return forwardMsg
    }
}
